package com.mo.ld.activity.interactive

import android.location.Criteria
import android.location.Geocoder
import android.location.Location
import android.view.View
import com.king.location.LocationClient
import com.king.location.LocationErrorCode
import com.king.location.OnExceptionListener
import com.king.location.OnLocationListener
import com.mo.ld.databinding.ActLoctionBinding
import com.mo.lib.ui.activity.BaseVbActivity
import com.mo.lib.utils.KLog
import com.xuexiang.constant.PermissionConstants
import com.xuexiang.xaop.annotation.Permission
import java.text.SimpleDateFormat
import java.util.*


/**
 * @ author：mo
 * @ data：2021/9/26:15:21
 * @ 功能：
 */
class LoctionActivity : BaseVbActivity<ActLoctionBinding>() {

    private val locationClient by lazy {
        LocationClient(this)
    }

    private val geocoder by lazy {
        Geocoder(this)
    }

    private val simpleDateFormat by lazy {
        SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    }

    private var isPermissionGranted = false


    override fun initData() {
        //可根据具体需求设置定位配置参数（这里只列出一些主要的参数）
        val locationOption = locationClient.getLocationOption()
            .setAccuracy(Criteria.ACCURACY_FINE)//设置位置精度：高精度
            .setPowerRequirement(Criteria.POWER_LOW) //设置电量消耗：低电耗
            .setMinTime(10000)//设置位置更新最小时间间隔（单位：毫秒）； 默认间隔：10000毫秒，最小间隔：1000毫秒
            .setMinDistance(0)//设置位置更新最小距离（单位：米）；默认距离：0米
            .setOnceLocation(false)//设置是否只定位一次，默认为 false，当设置为 true 时，则只定位一次后，会自动停止定位
            .setLastKnownLocation(true)//设置是否获取最后一次缓存的已知位置，默认为 true
        //设置定位配置参数
        locationClient.setLocationOption(locationOption)

        //设置定位监听
        locationClient.setOnLocationListener(object: OnLocationListener(){
            override fun onLocationChanged(location: Location) {
                //位置信息
                KLog.i("onLocationChanged(location = ${location})")
                val builder = StringBuilder()
                builder.append("Longitude: \t${location.longitude}\n")
                    .append("Latitude: \t${location.latitude}\n")

                //根据坐标经纬度获取位置地址信息（WGS-84坐标系）
                val list = geocoder.getFromLocation(location.latitude,location.longitude,1)
                list?.let {
                    builder.append("Address: \t${it[0].getAddressLine(0)}\n")
                }

                builder.append("Time: \t${simpleDateFormat.format(Date(location.time))}\n")
                    .append("Provider: \t${location.provider}\n")

                viewBinding.tvLoction.text = builder.toString()
            }

            override fun onProviderEnabled(provider: String) {
                super.onProviderEnabled(provider)
                KLog.i("onProviderEnabled(provider = ${provider})")
            }

            override fun onProviderDisabled(provider: String) {
                super.onProviderDisabled(provider)
                KLog.i("onProviderDisabled(provider = ${provider})")
            }

        })
        locationClient.setOnExceptionListener(object : OnExceptionListener {
            override fun onException(@LocationErrorCode errorCode: Int, e: Exception) {
                //定位出现异常
                KLog.i("onException(errorCode = ${errorCode}, e = ${e})")
                viewBinding.tvLoction.text = e.message
            }
        })

    }

    @Permission(PermissionConstants.LOCATION)
    override fun onClickView(view: View) {
        super.onClickView(view)
        startLocation()
    }
    /**
     * 开始定位
     */
    private fun startLocation(){
        if(locationClient.isStarted()){//如果已经开始定位，则先停止定位
            locationClient.stopLocation()
        }
        viewBinding.tvLoction.text = "Start location..."
        locationClient.startLocation()

    }
}